package com.smile.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.smile.data.dto.AuthLoginDto
import com.smile.data.entity.UserEntity
import com.smile.data.result.AuthLoginResult
import com.smile.mapper.StoreMapper
import com.smile.mapper.UserMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
import com.smile.utils.JwtUtils

@Service
@Component
class AuthService {
    @Autowired
    lateinit var userMapper: UserMapper

    @Autowired
    lateinit var mapper: StoreMapper

    @Autowired
    lateinit var redisTemplate: RedisTemplate<String,String>
//
//    @Autowired
//    lateinit var authenticationManager: AuthenticationManager
//
//    @Autowired
//    lateinit var bCryptPasswordEncoder: BCryptPasswordEncoder
//
//    @Autowired
//    lateinit var sender: JavaMailSender

    @Value("\${spring.mail.username}")
    private val form: String? = null

    fun login(dto: AuthLoginDto): AuthLoginResult {
        val password: String? = dto.password;
        val username: String? = dto.username;
        if (password.isNullOrEmpty() || username.isNullOrEmpty()) throw RuntimeException("账号或密码不能为空!")
//        val authenticationToken = UsernamePasswordAuthenticationToken(username, password, null)
//        authenticationManager.authenticate(authenticationToken)
        val wrapper: LambdaQueryWrapper<UserEntity> = LambdaQueryWrapper();
        wrapper.eq(UserEntity::username, username)
        val user: UserEntity = userMapper.selectOne(wrapper)
        val token: String = JwtUtils().createToken(username, user.id)
        redisTemplate!!.opsForValue()
            .set(dto.username + "Authorization", token, (60 * 60 * 24).toLong(), TimeUnit.SECONDS)
        return AuthLoginResult(token);
    }
//
//    fun code(email: String): Result {
//        return try {
//            if (email.isEmpty()) throw RuntimeException("邮箱不能为空!")
//            val mailMessage = SimpleMailMessage()
//            val random = Random()
//            val code = random.nextInt(899999) + 100000
//            redisTemplate!!.opsForValue().set("email$email", code)
//            mailMessage.setSubject("注册码")
//            mailMessage.setText("" + code)
//            mailMessage.setTo(email)
//            mailMessage.setFrom(form)
//            sender!!.send(mailMessage)
//            Result.build()
//        } catch (e: Exception) {
//            throw RuntimeException(e.message)
//        }
//    }
//
//    fun register(dto: AuthRegisterDto): Result {
//        val code: String = dto.getCode()
//        val user = UserEntity()
//        user.setEmail(dto.getEmail())
//        user.setPassword(dto.getPassword())
//        user.setUsername(dto.getUsername())
//        if (StringUtils.isBlank(code)) throw RuntimeException("验证码不能为空!")
//        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(
//                user.getEmail()
//            )
//        ) throw RuntimeException("账号或密码不可为空!")
//        val wrapper: LambdaQueryWrapper<UserEntity> = LambdaQueryWrapper<UserEntity>()
//        wrapper.eq(UserEntity::getUsername, user.getUsername())
//        val users: UserEntity = userMapper.selectOne(wrapper)
//        if (users != null) throw RuntimeException("账号已存在")
//        val email: String = user.getEmail()
//        val res: Any = redisTemplate!!.opsForValue()["email$email"].toString()
//        if (res == null || res != code) throw RuntimeException("验证码错误!")
//        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()))
//        val i: Int = userMapper.insert(user)
//        if (i > 0) {
//            redisTemplate.delete("email$email")
//            return Result.build("OK")
//        }
//        throw RuntimeException("注册失败，请重新注册")
//    }
//
//    fun queryStore(): Result {
//        val storeVos: List<StoreVo> = mapper.queryStore("18783116545")
//        return Result.build(storeVos)
//    }
}
